package com.ruoyi.vplat.websocket.listener;

import java.util.Map;

import javax.websocket.Session;

import org.springframework.beans.factory.annotation.Autowired;

import com.ruoyi.common.websocket.listener.WsOpenListener;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.vplat.domain.VplatGateway;
import com.ruoyi.vplat.service.IVplatDeviceService;
import com.ruoyi.vplat.service.IVplatGatewayService;
import com.ruoyi.vplat.service.IVplatVideoService;

public abstract class AbstractWsOpenListener implements WsOpenListener {
	@Autowired
	protected IVplatGatewayService gatewayService;
	@Autowired
	protected ISysDictDataService dictDataService;
	@Autowired
	protected IVplatDeviceService vplatDeviceService;
	@Autowired
	protected IVplatVideoService vplatVideoService;

	/**
	 * @param username
	 * @param protocol
	 * @param name
	 */
	private void saveOrUpdate(String username, String protocol, String name) {
		VplatGateway gateway = gatewayService.selectById(username);
		if (gateway == null) {
			gateway = new VplatGateway();
			gateway.setId(username);
			// select * from sys_dict_data where dict_type = 'vplat_device_protocol'
			gateway.setProtocol(protocol);
			gateway.setName(name);
			gateway.setStatus("0");
			gatewayService.insert(gateway);
		}else{
			gateway.setOnline(1);
			gateway.setName(name);
			gatewayService.update(gateway);
		}
	}

	/**
	 * @param username
	 * @param session
	 * @param gatewayType
	 * @return
	 */
	public String saveOrUpdateGateway(String username, Session session, String gatewayType,String protocol) {
		Map<String, Object> userProperties = session.getUserProperties();
		String clientIp = (String) userProperties.get("clientIp");
		String name = clientIp + "-" + gatewayType;
//		if (username.contains("-")) {
//			int index = username.indexOf("-");
//			username = username.substring(index + 1);
//		}
		saveOrUpdate(username, protocol, name);
		return username;
	}
}
